import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:base_flutter/base_flutter.dart';

import '../util/ext_utils.dart';

class PermissionManagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PermissionManageState();
}

class _PermissionManageState extends State<PermissionManagePage> with WidgetsBindingObserver{
  Map<Permission,dynamic> permissionMap = {};
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text("应用权限管理"),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CommonText('为了向您提供更好的用户体验\n我们会在特定场景下向您申请以下手机系统权限',textSize: 13,textColor: Colours.gray_66).addToContainer(
              margin: EdgeInsets.symmetric(horizontal: 12,vertical: 12)
            ),
            ...permissionMap.entries.map((item) {
              return _buildPermissionItem(item.key, item.value);
            }).toList().insertWidget(Gaps.dividerLine)
          ],
        ),
      ),
    );
  }

  Widget _buildPermissionItem(Permission permission, dynamic info) {
    return Row(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CommonText(info['title']??""),
            SizedBox(height: 5,),
            CommonText(info['msg']??"",textSize: 13,textColor: Colours.gray_66),
          ],
        ).setWeight(1),
        CommonText(info['setName'],textSize: 14,),
        Icon(Icons.arrow_forward_ios,size: 16,)
      ],
    ).addToContainer(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 12,vertical: 14)
    ).onTap(() async {
      await openAppSettings();
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((duration) async {
      var isAndroid13 = await isAndroid13OrAbove();
      permissionMap.addAll(PermissionCenterConfig.permissionMap);
      if(isAndroid13){
        permissionMap.remove(Permission.storage);
      }else{
        permissionMap.remove(Permission.photos);
      }
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      PermissionCenterConfig.initPermissionConfig().then((i){
        setState(() {});
      });

    }
  }

}
